/*
Copyright 2023.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controller

import (
	"context"
	"gitee.com/amoyx/devops-infras/internal/tencentcloud"
	"github.com/go-logr/logr"
	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
	"strconv"
	"strings"
	"time"

	appv1 "gitee.com/amoyx/devops-infras/api/v1"
)

// RedisReconciler reconciles a Redis object
type RedisReconciler struct {
	client.Client
	Scheme *runtime.Scheme
	tencentcloud.RedisCloud
}

//+kubebuilder:rbac:groups=resources.factory.sandload.com,resources=redis,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=resources.factory.sandload.com,resources=redis/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=resources.factory.sandload.com,resources=redis/finalizers,verbs=update

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Redis object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.15.0/pkg/reconcile
//var redis appv1.Redis

func (r *RedisReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	logger := log.FromContext(ctx)

	var redis appv1.Redis

	if err := r.Get(ctx, req.NamespacedName, &redis); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	// 查询到成功状态，结束流程
	if redis.Status.Status == appv1.SuccessStatus {
		return ctrl.Result{}, nil
	}

	switch {
	case len(redis.Status.Instances) < 1:
		r.execCreate(logger, ctx, &redis)
	case len(redis.Status.Instances) >= 1:
		if err := r.enableWanAddr(logger, ctx, &redis); err != nil {
			return ctrl.Result{}, nil
		}
		fallthrough
	default:
		r.queryStatus(logger, ctx, &redis)
	}

	// 查询到失败状态，结束流程
	if redis.Status.Status == appv1.FailStatus {
		return ctrl.Result{}, nil
	}

	return ctrl.Result{RequeueAfter: time.Second * 10}, nil
}

// execCreate 执行创建动作
func (r *RedisReconciler) execCreate(logger logr.Logger, ctx context.Context, redis *appv1.Redis) {
	res, err := r.CreateRedis(redis)
	if err != nil {
		logger.Error(err, "创建redis失败")
		redis.Status.Message = err.Error()
		return
	}

	for _, id := range res.InstanceIds {
		redis.Status.Instances = append(redis.Status.Instances, appv1.RedisInstance{Id: *id})
	}

	redis.Status.Status = appv1.CreatingStatus
	if err = r.Status().Update(ctx, redis); err != nil {
		logger.Error(err, "更新redis状态失败")
		redis.Status.Status = appv1.FailStatus
	}
}

// queryStatus 查询实例状态
func (r *RedisReconciler) queryStatus(logger logr.Logger, ctx context.Context, redis *appv1.Redis) {
	for index, instance := range redis.Status.Instances {
		res, err := r.DescribeRedis(instance.Id)
		if err != nil {
			logger.Error(err, instance.Id+"redis实例查询错误")
			continue
		}

		if *res.InstanceSet[0].Status != 2 {
			redis.Status.Instances[index].Message = "实例创建中"
			redis.Status.Instances[index].Status = appv1.CreatingStatus
			redis.Status.Status = appv1.CreatingStatus
			logger.Info("redis实例正在创建中")
			continue
		}

		redis.Status.Instances[index].Status = appv1.SuccessStatus
		redis.Status.Instances[index].Message = "实例运行中"
		redis.Status.Instances[index].PrivateAddress = *res.InstanceSet[0].WanIp + ":" + strconv.FormatInt(*res.InstanceSet[0].Port, 10)
		if strings.TrimSpace(*res.InstanceSet[0].WanAddress) != "" {
			redis.Status.Instances[index].WanAddress = *res.InstanceSet[0].WanAddress
			redis.Status.Instances[index].ExternalStatus = appv1.SuccessStatus
			redis.Status.Status = appv1.SuccessStatus
			logger.Info("公网地址开通成功")
			continue
		}
		redis.Status.Instances[index].ExternalStatus = appv1.CreatingStatus
		redis.Status.Status = appv1.CreatingStatus
	}
	if err := r.Status().Update(ctx, redis); err != nil {
		logger.Error(err, "更新redis状态失败")
		redis.Status.Status = appv1.FailStatus
	}
}

// modifyWanAddr 开启公网地址
func (r *RedisReconciler) enableWanAddr(logger logr.Logger, ctx context.Context, redis *appv1.Redis) error {
	for index, v := range redis.Status.Instances {
		if v.ExternalStatus == appv1.SuccessStatus || v.ExternalStatus == appv1.CreatingStatus {
			continue
		}
		logger.Info("正在开通公网地址。。")
		err := r.RedisWanAddress(v.Id, true)
		if err != nil {
			logger.Error(err, "redis开启公网IP失败")
			redis.Status.Message = err.Error()
		}

		redis.Status.Instances[index].ExternalStatus = appv1.CreatingStatus
		if err = r.Status().Update(ctx, redis); err != nil {
			logger.Error(err, "更新redis开启公网IP状态失败")
			redis.Status.Status = appv1.FailStatus
			return err
		}
	}
	return nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *RedisReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&appv1.Redis{}).
		Complete(r)
}
